const path = require('path')
const app = require('../app')
const {fileUploadError,fileTypeError,publishGoodsError,updateErrorGoods,invalidGoodsID,deleteGoodsError,restpreErrpr} = require('../consitant/err.type')

const {createGoods,updateGoods,removeGoods,restore,findGoods} = require('../service/goods.service')
class GoodsController{

  async upload(ctx,next) {
    // console.log(ctx.request.files.file.type)
    const {file} = ctx.request.files
    const fileTypes = ['image/jpeg','image/png']
    
    if(file){
      if(!fileTypes.includes(file.type)){
        return ctx.app.emit('error',fileTypeError,ctx)
      }
      ctx.body = {
        code:'0',
        message:'图片上传成功',
        result:{
          goods_img:path.basename(file.path),
        }
      }
    }else{
      return ctx.app.emit('error',fileUploadError,ctx)
    }
    
  }
  
  async create(ctx) {
    //调用service的createGoods方法
    try{
      const {createdAt,updatedAt,...res} = await createGoods(ctx.request.body)
 
      ctx.body = {
        code:0,
        message:'发布商品成功',
        result:res
      }
    }catch(err){
      console.error(err)
      return ctx.app.emit('error',publishGoodsError,ctx)
    }
   
  }

  async update(ctx) {
    //校验id
 try{
  ctx.verifyParams({
    id: {
      type: 'number',
      required: true,
    },
  })
 
  const res =  await updateGoods(ctx.request.body)
   if(res){
     ctx.body = {
       code:0,
       message:'修改商品成功',
       result:ctx.request.body
     }
   }else{
   return ctx.app.emit('error',invalidGoodsID,ctx)
   }
 }catch(err){
  console.error(err)
  ctx.app.emit('error',updateErrorGoods,ctx)
 }
   
  }

  async deletegoods(ctx) {
 try{
  const res =  await removeGoods(ctx.request.body.id)
  console.log(res)
  if(res){
    ctx.body = {
      code:0,
      message:'下架商品成功',
      result:'下架成功还不开心吗？我的前端'
    }
  }else{
    ctx.app.emit('error',deleteGoodsError,ctx)
  }
 }catch(err){
  console.error(err)
 }
  }

  async restoregoods(ctx){

    const res = await restore(ctx.request.body.id)

    if(res){
      ctx.body = {
        code:0,
        message:'商品上架成功',
        result:"成功啦！我的宝贝！爱你哦 我的宝贝嘿嘿"
      }
    }else{
      ctx.app.emit('error',restpreErrpr,ctx)
    }
  
  }

  async findAll(ctx){
    //解析出pageNumhe pageSzie
    //调用数据处理的相关方法
    //返回结果
    const {pageNum = 1,pageSize = 10} = ctx.request.query
    console.log(ctx.request.query)
    const res = await findGoods(pageNum,pageSize)

    ctx.body = {
      code:0,
      message:'获取商品数据成功',
      resulr:res
    }
  }

}
module.exports = new GoodsController()